<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "category".
 *
 * @property integer $id
 * @property integer $pid
 * @property string $name
 * @property string $py
 * @property string $keyword
 * @property string $info
 * @property string $title
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'category';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','py','title'], 'required'],
            [['pid'], 'integer'],
            [['name', 'py'], 'string', 'max' => 50],
            [['keyword','title'], 'string', 'max' => 255],
            [['info'], 'string', 'max' => 500],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'pid' => Yii::t('app', '父级分类'),
            'name' => Yii::t('app', '分类名称'),
            'py' => Yii::t('app', '分类拼音'),
            'keyword' => Yii::t('app', '关键词'),
            'info' => Yii::t('app', '简介'),
            'title' => Yii::t('app', '标题'),
        ];
    }

    public function beforeSave($insert)
    {
        if(empty($this->pid)){
            $this->pid = 0;
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    /**
     * Get all catalog order by parent/child with the space before child label
     * Usage: ArrayHelper::map(Catalog::get(0, Catalog::find()->asArray()->all()), 'id', 'label')
     * @param int $parentId  parent catalog id
     * @param array $array  catalog array list
     * @param int $level  catalog level, will affect $repeat
     * @param int $add  times of $repeat
     * @param string $repeat  symbols or spaces to be added for sub catalog
     * @return array  catalog collections
     */
    static public function get($parentId = 0, $array = [], $level = 0, $add = 2, $repeat = '　')
    {
        $strRepeat = '';
        // add some spaces or symbols for non top level categories
        if ($level > 1) {
            for ($j = 0; $j < $level; $j++) {
                $strRepeat .= $repeat;
            }
        }

        $newArray = array ();
        //performance is not very good here
        foreach ((array)$array as $v) {
            if ($v['pid'] == $parentId) {
                $item = (array)$v;
                $item['label'] = $strRepeat . $v['name'];
                $newArray[] = $item;

                $tempArray = self::get($v['id'], $array, ($level + $add), $add, $repeat);
                if ($tempArray) {
                    $newArray = array_merge($newArray, $tempArray);
                }
            }
        }
        return $newArray;
    }
}
